﻿using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using UtilZ.Dotnet.Ex.Communication.Base;
using UtilZ.Dotnet.Ex.Communication.Net.Udp;
using UtilZ.Dotnet.Ex.Log;

namespace ConAppCore
{
    internal class TestNetUdpClient
    {
        private static NetUdpClient _netUdpClient = null;
        public static void Test()
        {
            IUnpacker unpacker = new NetUDPUnpacker();
            unpacker.PackOutput += Unpacker_PackOutput;
            IPEndPoint locaEndPoint = new IPEndPoint(IPAddress.Parse("192.168.200.196"), 30001);
            var initPara = new NetUdpClientInitPara(unpacker, locaEndPoint);
            _netUdpClient = new NetUdpClient(initPara);

            IPEndPoint dstEndPoint = new IPEndPoint(IPAddress.Parse("192.168.200.196"), 50001);
            byte[] buffer = new byte[] { 11, 12, 13, 45 };
            _netUdpClient.SendTo(buffer, 0, buffer.Length, System.Net.Sockets.SocketFlags.None, dstEndPoint);
        }

        private static void Unpacker_PackOutput(object sender, DataOutputArgs e)
        {
            Loger.Info($"收到udp数据包,长度:{e.Data.Length}");
        }



        private static void TestSendBroadcast2()
        {
            // 组播地址和端口
            IPAddress multicastAddress = IPAddress.Parse("239.255.255.250");
            int multicastPort = 1900;

            // 创建Socket
            Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);

            // 设置TTL（Time To Live）
            socket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.MulticastTimeToLive, 1);

            // 加入组播组
            socket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, new MulticastOption(multicastAddress));

            // 要发送的数据
            string message = "Hello, Multicast!";
            byte[] buffer = Encoding.UTF8.GetBytes(message);

            // 发送数据到组播地址
            IPEndPoint endPoint = new IPEndPoint(multicastAddress, multicastPort);
            socket.SendTo(buffer, endPoint);

            Console.WriteLine($"Sent: {message} to {multicastAddress}:{multicastPort}");

            // 离开组播组
            socket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.DropMembership, new MulticastOption(multicastAddress));

            // 关闭Socket
            socket.Close();

        }

        private static void TestReceiveBroadcast()
        {

            // 组播地址和端口
            IPAddress multicastAddress = IPAddress.Parse("239.255.255.250");
            int multicastPort = 1900;
            IPAddress localAddress = IPAddress.Any;

            // 创建 Socket
            Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);

            try
            {
                // 绑定到本地 IP 地址和端口
                IPEndPoint localEndPoint = new IPEndPoint(localAddress, multicastPort);
                socket.Bind(localEndPoint);

                // 加入组播组
                socket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, new MulticastOption(multicastAddress, localAddress));

                Console.WriteLine("加入组播组，开始接收数据...");

                // 接收数据
                byte[] buffer = new byte[1024];
                while (true)
                {
                    EndPoint remoteEndPoint = new IPEndPoint(IPAddress.Any, 0);
                    int bytesReceived = socket.ReceiveFrom(buffer, ref remoteEndPoint);

                    string receivedData = Encoding.UTF8.GetString(buffer, 0, bytesReceived);
                    Console.WriteLine($"从 {remoteEndPoint} 接收到数据: {receivedData}");
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"发生错误: {ex.Message}");
            }
            finally
            {
                // 关闭 Socket
                socket.Close();
            }
        }
    }

}
